<template>
  <div class="main">
    <el-button
      type="primary"
      :icon="useRenderIcon('ep:plus')"
      @click="openDialog"
    >
      创建服务
    </el-button>
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-[99/100] pt-[12px] overflow-auto"
    >
      <el-form-item label="关键字" prop="keyword">
        <el-input
          v-model="form.keyword"
          placeholder="搜索关键字"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item label="状态" prop="onlyEnabled">
        <el-select
          v-model="form.onlyEnabled"
          placeholder="请选择"
          clearable
          class="!w-[150px]"
        >
          <el-option label="启用" :value="true" />
          <el-option label="禁用" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="服务分类" prop="category">
        <el-input
          v-model="form.category"
          placeholder="搜索服务分类"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
        <el-button
          :icon="useRenderIcon(Refresh)"
          type="success"
          @click="syncService"
        >
          同步服务
        </el-button>
      </el-form-item>
    </el-form>

    <el-table
      show-overflow-tooltip
      stripe
      border
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column prop="sortOrder" label="序号" width="100" />
      <el-table-column prop="id" label="ID" width="100" />
      <el-table-column
        prop="standardCode"
        label="服务代码"
        width="160"
        sortable
      />
      <el-table-column
        prop="displayName"
        label="名称"
        min-width="160"
        sortable
      />
      <el-table-column prop="displayImage" label="图片" width="180">
        <template #default="{ row }">
          <div class="img-box">
            <el-image
              :src="taskConfigStore.getIcon(row.standardCode)"
              fit="cover"
              style="height: 40px; width: 120px"
            >
              <template #error>
                <div class="image-slot">暂无图片</div>
              </template>
            </el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="defaultScore" label="价格" />
      <el-table-column
        prop="serverProvides"
        label="API提供商"
        width="160"
        sortable
      />
      <el-table-column prop="platform" label="平台代码" width="120" sortable />
      <el-table-column
        prop="functionType"
        label="功能类型代码"
        width="140"
        sortable
      />
      <!-- <el-table-column prop="needGear" label="是否需要gear" width="120" /> -->
      <el-table-column
        prop="enabled"
        label="是否启用"
        width="120"
        :formatter="formatterEnabled"
      />
      <el-table-column
        prop="createTime"
        :formatter="val => handleAutoUTC8(val.createTime)"
        label="创建时间"
        width="180"
        sortable
      />
      <el-table-column
        prop="updateTime"
        :formatter="val => handleAutoUTC8(val.updateTime)"
        label="更新时间"
        width="180"
        sortable
      />
      <el-table-column label="操作" fixed="right" width="420">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="openSort(scope.row)"
          >
            更新排序
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            @click="openChangeDialog(scope.row.standardCode)"
          >
            切换供应商
          </el-button>
          <el-popconfirm
            width="220"
            :icon="InfoFilled"
            icon-color="#626AEF"
            :title="`确定${scope.row.enabled ? '禁用' : '启用'}该服务类型吗？`"
            @confirm="confirmStatus(scope.row)"
          >
            <template #reference>
              <el-button
                link
                :type="scope.row.enabled ? 'danger' : 'success'"
                size="small"
              >
                {{ scope.row.enabled ? "禁用" : "启用" }}
              </el-button>
            </template>
            <template #actions="{ confirm, cancel }">
              <el-button size="small" @click="cancel">取消</el-button>
              <el-button type="danger" size="small" @click="confirm">
                确定
              </el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm
            width="220"
            :icon="InfoFilled"
            icon-color="#626AEF"
            title="确定要删除该服务类型吗？"
            @confirm="delateService(scope.row)"
          >
            <template #reference>
              <el-button link type="danger" size="small"> 删除 </el-button>
            </template>
            <template #actions="{ confirm, cancel }">
              <el-button size="small" @click="cancel">取消</el-button>
              <el-button type="danger" size="small" @click="confirm">
                确定
              </el-button>
            </template>
          </el-popconfirm>
          <el-button
            link
            type="success"
            size="small"
            @click="openIconDialog(scope.row.standardCode)"
          >
            上传图标
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            @click="openDialog(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            @click="copyService(scope.row)"
          >
            复制
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <ServiceIconDialog
      ref="serviceIconDialogRef"
      @refresh="resetForm(formRef)"
    />

    <ServiceTypeDialog
      ref="serviceTypeDialogRef"
      @refresh="resetForm(formRef)"
    />
    <ChangePrioDialog
      ref="changePrioDialogRef"
      :providerOptions
      @refresh="onSearch"
    />
    <ChangeSortDialog ref="changeSortDialogRef" @refresh="onSearch" />
  </div>
</template>

<script lang="ts" setup>
import { InfoFilled, Picture as IconPicture } from "@element-plus/icons-vue";
import { reactive, ref, onMounted, watch } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Refresh from "@iconify-icons/ep/refresh";
import {
  getAllServiceTypes,
  setServiceTypeStatus,
  deleteServiceType,
  syncServiceTypes
} from "@/api/adminServiceTypeApi";
import { getAllProviders } from "@/api/adminProvidersApi";
import { message } from "@/utils/message";
import ServiceTypeDialog from "./components/ServiceTypeDialog.vue";
import ServiceIconDialog from "./components/ServiceIconDialog.vue";
import ChangePrioDialog from "./components/ChangePrioDialog.vue";
import { sortList } from "@/utils/tools";
import { handleAutoUTC8 } from "@/utils/tools";
import ChangeSortDialog from "./components/ChangeSortDialog.vue";
import { useTaskConfigHook } from "@/store/modules/taskConfig";
const taskConfigStore = useTaskConfigHook();
const serviceIconDialogRef = ref();
const serviceTypeDialogRef = ref();
const changeSortDialogRef = ref();
const formRef = ref();
const loading = ref(false);
const form = reactive({
  category: "",
  keyword: "",
  onlyEnabled: false
});
const tableData = ref([]);
const changePrioDialogRef = ref(null);
const openChangeDialog = (standardCode: string) => {
  changePrioDialogRef.value?.open(standardCode);
};
const openDialog = (row: null | any) => {
  serviceTypeDialogRef.value.open(row);
};
const copyService = (row: null | any) => {
  const copyRow = { ...row };
  delete copyRow.id;
  serviceTypeDialogRef.value.open(copyRow);
};
const openSort = (row: null | any) => {
  changeSortDialogRef.value.open(row);
};
const openIconDialog = (code: string) => {
  serviceIconDialogRef.value.open(code);
};
const formatterEnabled = (row: any) => {
  return row.enabled ? "是" : "否";
};

async function onSearch() {
  const { success, data } = await getAllServiceTypes(form);
  if (success) {
    tableData.value = data.map(({ serviceType, providerConfigs }) => {
      const serverProvides = providerConfigs
        .filter(({ isActive }) => isActive)
        .map(({ apiProvider }) => apiProvider)
        .join("、");
      return {
        ...serviceType,
        providerConfigs,
        serverProvides
      };
    });
    tableData.value = sortList(tableData.value);
  }
}
const delateService = async ({ standardCode }) => {
  try {
    await deleteServiceType(standardCode);
    message("删除成功", { type: "success" });
    onSearch();
  } catch (error) {
    console.log(error);
  }
};
const confirmStatus = async row => {
  try {
    const { standardCode, enabled } = row;
    await setServiceTypeStatus(standardCode, !enabled);
    message("操作成功", { type: "success" });
    onSearch();
  } catch (error) {
    console.log(error);
  }
};
const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  onSearch();
};
const syncService = async () => {
  try {
    await syncServiceTypes();
    message("同步成功", { type: "success" });
    resetForm(formRef.value);
  } catch (error) {
    console.log(error);
  }
};
const providerOptions = ref([]);
onMounted(() => {
  onSearch();
  getAllProviders().then(res => {
    providerOptions.value = res.data.providers;
  });
});
</script>
<style lang="scss" scoped>
.main {
  padding: 20px;
  background-color: #fff;
  .el-pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }
}
.img-box {
  width: 100%;
  display: flex;
  justify-content: center;
  .image-slot {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
